package com.ibiaoke.order.service;

import com.google.common.collect.Lists;
import com.ibiaoke.common.exception.ServiceException;
import com.ibiaoke.common.response.Res;
import com.ibiaoke.common.utils.AssertUtils;
import com.ibiaoke.customer.entity.ThirdPartLogin;
import com.ibiaoke.customer.service.ThirdPartLoginService;
import com.ibiaoke.common.consts.BusinessDef;
import com.ibiaoke.marketing.consts.CouponGroupDef;
import com.ibiaoke.marketing.dao.CouponDao;
import com.ibiaoke.marketing.dao.CouponReceiveDao;
import com.ibiaoke.marketing.entity.Coupon;
import com.ibiaoke.marketing.entity.CouponReceive;
import com.ibiaoke.marketing.entity.vo.CouponReceiveVO;
import com.ibiaoke.marketing.service.CouponReceiveService;
import com.ibiaoke.marketing.service.CouponService;
import com.ibiaoke.order.consts.OrderStatusConst;
import com.ibiaoke.order.dao.OrderCouponShareDao;
import com.ibiaoke.order.entity.OrderCouponShare;
import com.ibiaoke.order.entity.OrderCouponShareExample;
import com.ibiaoke.order.entity.vo.OrderVO;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by huhaichao on 2017/5/24.
 */
@Service
public class OrderCouponShareServiceImpl implements OrderCouponShareService {

    @Autowired
    private CouponDao couponDao;
    @Autowired
    private CouponReceiveDao couponReceiveDao;
    @Autowired
    private OrderCouponShareDao orderCouponShareDao;

    @Autowired
    private OrderService orderInfoService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private CouponReceiveService couponReceiveService;
    @Autowired
    private ThirdPartLoginService thirdPartyService;


    @Override
    public boolean shareOrderCoupon(Integer userId, Integer orderId) {

        AssertUtils.notNull(orderId, "您还没有选择要分享的订单");
        OrderVO order = orderInfoService.getOrder(orderId);
        AssertUtils.notNull(order, "这笔订单不存在哦");
        boolean paid = order.getOrderStatus() == OrderStatusConst.PAID || order.getOrderStatus() == OrderStatusConst.DELIVERED
                || order.getOrderStatus() == OrderStatusConst.RECEIVED;
        AssertUtils.requireTrue(paid, "订单未付款不能分享红包");

        OrderCouponShareExample shareExample = new OrderCouponShareExample();
        shareExample.createCriteria().andOrderIdEqualTo(orderId.intValue());
        List<OrderCouponShare> orderCouponShares = orderCouponShareDao.selectByExample(shareExample);
        if (CollectionUtils.isEmpty(orderCouponShares)) {
            List<Coupon> coupons = couponDao.listCoupon(CouponGroupDef.SHARE_ORDER);
            AssertUtils.notEmpty(coupons, "未设置订单分享红包，请联系管理员");
            OrderCouponShare share = new OrderCouponShare();
            share.setOrderId(orderId.intValue());
            share.setCouponId(coupons.get(0).getCouponId());
            share.setUserId(userId);
            share.setCreateTime(new Date());
            share.setUpdateTime(new Date());
            orderCouponShareDao.insert(share);

        }
        return true;
    }

    @Override
    public Res receiveOrderShareCoupon(Integer userId, Integer orderId) {
        Res res = Res.create();
        if (orderId == null) {
            throw new ServiceException("分享订单错误");
        }
        OrderCouponShare couponShare = getShareByOrderId(orderId);
        if (couponShare == null) {
            throw new ServiceException("此订单未分享红包");
        }
        //领取优惠券
        Integer couponId = couponShare.getCouponId();
        Coupon coupon = couponService.getCoupon(couponId);
        try {
            couponReceiveService.receiveCouponWithBusiness(userId, coupon.getCouponId(), BusinessDef.SHARE_ORDER, couponShare.getShareId());
        } catch (ServiceException e) {
            res.addResponse("received", "received");
            res.addResponse("failReceiveReason", e.getLocalizedMessage());
        }
        //查询优惠券领取信息
        List<CouponReceive> couponReceives = couponReceiveDao.listCouponReceive(null, null, BusinessDef.SHARE_ORDER, couponShare.getShareId());

        List<CouponReceiveVO> couponReceiveVOs = couponReceiveService.convert(couponReceives);

        Optional<CouponReceive> receiveOptional = couponReceives.parallelStream()
                .filter(couponReceive -> couponReceive.getUserId().equals(userId)).findAny();
        CouponReceive myReceiveCoupon = receiveOptional.orElse(null);

        res.addResponse("couponReceives", couponReceiveVOs);
        res.addResponse("myReceiveCoupon", myReceiveCoupon);
        return res;
    }




    public OrderCouponShare getShareByOrderId(Integer orderId) {
        OrderCouponShareExample example = new OrderCouponShareExample();
        example.createCriteria().andOrderIdEqualTo(orderId);
        List<OrderCouponShare> shares = orderCouponShareDao.selectByExample(example);
        return CollectionUtils.isEmpty(shares) ? null : shares.get(0);
    }

}
